package com.jxzn.locust.support;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.jxzn.locust.exception.LoginExpiredException;
import com.jxzn.locust.model.Manager;

public enum LoginSession {

    USER_ID(true),

    USER_NAME(true),

    ROLE_ID(false),

    SUPPER(false);

    boolean required;

    private LoginSession(boolean required) {
        this.required = required;
    }

    public boolean isRequired() {
        return required;
    }

    public static String getItem(HttpSession session, LoginSession item) {
        Object o = session.getAttribute(item.name());
        if (null == o) {
            if (item.isRequired()) {
                throw new LoginExpiredException();
            } else {
                return StringUtils.EMPTY;
            }
        }
        return String.valueOf(o);
    }

    public static Manager getUser(HttpSession session) {
        Manager user = new Manager();
        user.setId(Integer.valueOf(LoginSession.getItem(session, USER_ID)));
        user.setName(LoginSession.getItem(session, USER_NAME));
        user.setRoleId(Integer.valueOf(LoginSession.getItem(session, ROLE_ID)));
        return user;
    }
}
